// 基础交互逻辑
document.addEventListener("DOMContentLoaded", () => {
    // 加载需求列表
    loadDemands(0);

    // 绑定分页按钮事件
    document.getElementById("prev-page").addEventListener("click", () => {
        if (currentPage > 0) {
            currentPage--;
            loadDemands(currentPage);
        }
    });

    document.getElementById("next-page").addEventListener("click", () => {
        if (currentPage < totalPages - 1) {
            currentPage++;
            loadDemands(currentPage);
        }
    });

    // 绑定导航栏点击事件
    document.querySelectorAll(".nav-item").forEach((item) => {
        item.addEventListener("click", async function () {
            const newTab = this.textContent.trim();

            // 如果正在切换或者点击当前标签，则不处理
            if (isTabSwitching || newTab === currentTab) {
                return;
            }

            try {
                isTabSwitching = true;

                // 更新导航项状态
                document.querySelector(".nav-item.active")?.classList.remove("active");
                this.classList.add("active");

                console.log("Switching to tab:", newTab);

                // 清理当前页面状态
                cleanupCurrentTab(currentTab);

                // 隐藏所有主要容器
                const allContainers = [
                    ".container",
                    ".messages-container",
                    ".demand-detail",
                    ".demand-grid",
                    ".pagination-container",
                ];

                allContainers.forEach((selector) => {
                    const container = document.querySelector(selector);
                    if (container) {
                        container.style.display = "none";
                    }
                });

                // 根据选中的导航项显示对应内容
                if (newTab === "需求广场") {
                    await switchToDemandSquare();
                } else if (newTab === "消息") {
                    await switchToMessages();
                }

                // 更新当前标签状态
                currentTab = newTab;
            } catch (error) {
                console.error("Error switching tabs:", error);
                showNotification("切换页面失败：" + error.message, "error");
            } finally {
                isTabSwitching = false;
            }
        });
    });

    // 初始化显示需求广场
    document.querySelector('.nav-item[data-tab="需求广场"]')?.click();
});

// 清理当前页面状态
function cleanupCurrentTab(tab) {
    if (tab === "需求广场") {
        // 清理需求广场相关状态
        const demandGrid = document.querySelector(".demand-grid");
        if (demandGrid) {
            demandGrid.innerHTML = "";
        }
    } else if (tab === "消息") {
        // 清理消息页面相关状态
        const messageList = document.querySelector(".message-list");
        if (messageList) {
            messageList.innerHTML = "";
        }
        // 重置消息相关变量
        currentSelectedDemandId = null;
    }
}

// 切换到需求广场
async function switchToDemandSquare() {
    const container = document.querySelector(".container");
    const demandGrid = document.querySelector(".demand-grid");
    const pagination = document.querySelector(".pagination-container");

    if (container) container.style.display = "flex";
    if (demandGrid) demandGrid.style.display = "grid";
    if (pagination) pagination.style.display = "flex";

    // 重新加载需求列表
    await loadDemands(currentPage);
}

// 切换到消息页面
async function switchToMessages() {
    const messagesContainer = document.querySelector(".messages-container");
    if (messagesContainer) {
        messagesContainer.style.display = "flex";

        // 确保消息列表和回复框都正确显示
        const messageList = document.querySelector(".message-list");
        const replyBox = document.querySelector(".reply-box");
        if (messageList) messageList.style.display = "block";
        if (replyBox) replyBox.style.display = "none"; // 初始隐藏回复框

        // 加载专家评论过的需求列表
        await loadExpertCommentedDemands();
    }
}

// 更新loadExpertCommentedDemands函数
async function loadExpertCommentedDemands() {
    try {
        console.log("Loading expert commented demands for userId:", userId);

        // 获取专家评论过的需求列表
        const demandsResponse = await fetch(
            `/api/comments/expert/${userId}/demands`
        );
        if (!demandsResponse.ok) {
            throw new Error(`获取需求列表失败: ${demandsResponse.status}`);
        }
        const demands = await demandsResponse.json();
        console.log("Received demands:", demands);

        if (!Array.isArray(demands) || demands.length === 0) {
            const demandList = document.querySelector(
                ".messages-container .left-nav"
            );
            demandList.innerHTML = "<div class='no-demands'>暂无消息</div>";
            document.querySelector(".message-list").innerHTML = "";
            document.querySelector(".demand-name").textContent = "";
            return;
        }

        // 获取所有需求的最新消息时间
        const demandIds = demands.map((demand) => demand.id);
        const latestMessagesResponse = await fetch(
            `/api/comments/demand/latest-time?${new URLSearchParams({
                demandIds: demandIds.join(","),
            })}`
        );
        if (!latestMessagesResponse.ok) {
            throw new Error("获取最新消息时间失败");
        }
        const latestMessages = await latestMessagesResponse.json();
        console.log("Latest messages:", latestMessages);

        // 添加最新消息时间到需求对象
        const demandsWithTime = demands.map((demand) => ({
            ...demand,
            latestMessageTime: latestMessages[demand.id] || new Date(0).toISOString(),
        }));

        // 按最新消息时间排序
        demandsWithTime.sort(
            (a, b) => new Date(b.latestMessageTime) - new Date(a.latestMessageTime)
        );

        const demandList = document.querySelector(".messages-container .left-nav");
        demandList.innerHTML = "";

        // 添加每个需求到左侧导航
        for (const demand of demandsWithTime) {
            const demandItem = document.createElement("div");
            demandItem.className = "demand-item";
            demandItem.setAttribute("data-demand-id", demand.id);

            const titleSpan = document.createElement("span");
            titleSpan.textContent = demand.title || "未命名需求";
            demandItem.appendChild(titleSpan);

            // 获取未读评论数
            const unreadCount = await fetch(
                `/api/comments/demand/${demand.id}/unread/count`
            );
            if (unreadCount.ok) {
                const count = await unreadCount.json();
                if (count > 0) {
                    const badge = document.createElement("span");
                    badge.className = "unread-badge";
                    badge.textContent = count;
                    demandItem.appendChild(badge);
                }
            }

            demandItem.addEventListener("click", () => {
                console.log("Demand item clicked:", demand.id, demand.title);
                showDemandMessages(demand.id, demand.title);
            });
            demandList.appendChild(demandItem);
        }

        // 如果有需求，默认显示第一个需求的消息
        if (demandsWithTime.length > 0) {
            console.log("Showing first demand:", demandsWithTime[0]);
            showDemandMessages(demandsWithTime[0].id, demandsWithTime[0].title);
        }
    } catch (error) {
        console.error("Error loading expert commented demands:", error);
        alert("加载需求列表失败：" + error.message);
    }
}

// 添加防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 添加节流函数
function throttle(func, limit) {
    let inThrottle;
    return function (...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => (inThrottle = false), limit);
        }
    };
}

// 优化后的showDemandMessages函数
async function showDemandMessages(demandId, demandTitle) {
    try {
        console.log("Showing messages for demand:", demandId, demandTitle);
        currentSelectedDemandId = demandId;

        // 更新UI状态
        updateUIState(demandId, demandTitle);

        // 显示加载状态
        showLoadingState();

        // 获取评论数据
        const allComments = await fetchComments(demandId);

        // 更新评论列表
        await updateCommentsList(allComments);

        // 设置滚动监听
        setupScrollListener();

        // 确保消息容器可见
        const messagesContainer = document.querySelector(".messages-container");
        if (messagesContainer) {
            messagesContainer.style.display = "flex";
        }

        // 滚动到顶部
        const scrollContainer = document.querySelector(
            ".comments-scroll-container"
        );
        if (scrollContainer) {
            scrollContainer.scrollTop = 0;
        }

        // 标记评论为已读
        markCommentsAsRead(allComments);
    } catch (error) {
        console.error("Error showing demand messages:", error);
        showNotification("加载消息失败：" + error.message, "error");
    }
}

// 更新UI状态
function updateUIState(demandId, demandTitle) {
    // 更新需求项选中状态
    document.querySelectorAll(".demand-item").forEach((item) => {
        item.classList.remove("active");
        if (item.getAttribute("data-demand-id") === demandId.toString()) {
            item.classList.add("active");
            // 移除未读标记
            const badge = item.querySelector(".unread-badge");
            if (badge) badge.remove();
        }
    });

    // 更新标题和需求信息
    const demandName = document.querySelector(".demand-name");
    if (demandName) {
        demandName.textContent = demandTitle;
        demandName.style.fontWeight = "500";
        demandName.style.fontSize = "16px";
        demandName.style.color = "#333";
    }
}

// 显示加载状态
function showLoadingState() {
    const messageList = document.querySelector(".message-list");
    if (messageList) {
        messageList.innerHTML = Array(3)
            .fill(0)
            .map(
                () => `
          <div class="comment-item loading-item">
              <div class="loading loading-avatar"></div>
              <div class="loading-content">
                  <div class="loading loading-text" style="width: 120px"></div>
                  <div class="loading loading-text"></div>
                  <div class="loading loading-text" style="width: 80%"></div>
              </div>
          </div>
      `
            )
            .join("");
    }
}

// 获取评论数据
async function fetchComments(demandId) {
    const response = await fetch(`/api/comments/demand/${demandId}`);
    if (!response.ok) throw new Error("获取评论失败");
    return await response.json();
}

// 更新评论列表
async function updateCommentsList(allComments) {
    const mainComments = allComments.filter((comment) => !comment.parentId);
    const replies = allComments.filter((comment) => comment.parentId);

    // 更新评论总数
    const totalCommentsElement = document.querySelector(".total-comments");
    if (totalCommentsElement) {
        totalCommentsElement.textContent = allComments.length;
    }

    const messageList = document.querySelector(".message-list");
    if (!messageList) return;

    messageList.innerHTML = "";

    // 使用DocumentFragment优化DOM操作
    const fragment = document.createDocumentFragment();

    // 按时间倒序排序主评论
    mainComments.sort(
        (a, b) => new Date(b.createdTime) - new Date(a.createdTime)
    );

    // 批量创建评论元素
    await Promise.all(
        mainComments.map(async (comment) => {
            const commentElement = await createCommentElement(comment, replies);
            fragment.appendChild(commentElement);
        })
    );

    messageList.appendChild(fragment);
}

// 设置滚动监听
function setupScrollListener() {
    const scrollContainer = document.querySelector(".comments-scroll-container");
    if (!scrollContainer) return;

    if (!scrollContainer._hasScrollListener) {
        scrollContainer._hasScrollListener = true;
        scrollContainer.style.overflowY = "auto";
        scrollContainer.style.height = "calc(100vh - 250px)";
        scrollContainer.style.paddingRight = "16px";

        // 使用节流函数优化滚动处理
        scrollContainer.addEventListener(
            "scroll",
            throttle(function () {
                const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
                // 如果滚动到底部附近，可以在这里加载更多评论
                if (scrollHeight - scrollTop <= clientHeight + 100) {
                    // loadMoreComments(); // 如果需要无限滚动可以实现这个函数
                }
            }, 100)
        );
    }
}

// 优化评论元素创建
async function createCommentElement(comment, allReplies) {
    const commentElement = document.createElement("div");
    commentElement.className = "comment-item";
    commentElement.setAttribute("data-comment-id", comment.id);

    // 并行获取用户信息和过滤回复
    const [userInfo, commentReplies] = await Promise.all([
        fetchUserInfo(comment.userId),
        filterReplies(allReplies, comment.id),
    ]);

    // 使用模板字符串一次性设置innerHTML
    commentElement.innerHTML = generateCommentHTML(
        comment,
        userInfo,
        commentReplies
    );

    // 添加事件监听
    setupCommentEventListeners(commentElement, comment, userInfo, commentReplies);

    return commentElement;
}

// 获取用户信息
async function fetchUserInfo(userId) {
    try {
        const response = await fetch(`/api/user/info?userId=${userId}`);
        if (!response.ok) throw new Error("获取用户信息失败");
        return await response.json();
    } catch (error) {
        console.error("Error fetching user info:", error);
        return {
            username: "未知用户",
            avatarUrl: "/images/default-avatar.png",
        };
    }
}

// 过滤回复
function filterReplies(allReplies, commentId) {
    return allReplies.filter((reply) => reply.parentId === commentId);
}

// 生成评论HTML
function generateCommentHTML(comment, userInfo, commentReplies) {
    return `
        <div class="comment-avatar">
            <img src="${
        userInfo.avatarUrl || `/api/user/avatar/image/${comment.userId}`
    }" 
                 alt="用户头像" 
                 onerror="handleAvatarError(this)"
                 loading="lazy">
        </div>
        <div class="comment-content">
            <div class="comment-user">${
        userInfo.username || comment.userName
    }</div>
            <div class="comment-text">${comment.content}</div>
            <div class="comment-actions">
                <span class="comment-time">${formatDateTime(
        comment.createdTime
    )}</span>
                <button class="reply-button">回复</button>
            </div>
            ${generateRepliesPreviewHTML(commentReplies)}
            ${generateReplyBoxHTML(userInfo)}
        </div>
    `;
}

// 设置评论事件监听
function setupCommentEventListeners(
    commentElement,
    comment,
    userInfo,
    commentReplies
) {
    // 回复按钮事件
    const replyButton = commentElement.querySelector(".reply-button");
    const replyBox = commentElement.querySelector(".reply-box");
    replyButton.addEventListener("click", () => {
        replyBox.style.display =
            replyBox.style.display === "none" ? "flex" : "none";
    });

    // 回复列表展开/收起事件
    const repliesCount = commentElement.querySelector(".replies-count");
    const repliesList = commentElement.querySelector(".replies-list");
    if (repliesCount && repliesList) {
        repliesCount.addEventListener("click", () => {
            const isHidden = repliesList.style.display === "none";
            repliesList.style.display = isHidden ? "block" : "none";
            repliesCount.textContent = isHidden
                ? `收起回复`
                : `查看 ${commentReplies.length} 条回复`;
        });
    }

    // 发送回复事件
    setupReplySubmission(commentElement, comment);
}

// 优化回复提交
function setupReplySubmission(commentElement, comment) {
    const confirmBtn = commentElement.querySelector(".reply-box .confirm-btn");
    const replyTextarea = commentElement.querySelector(
        ".reply-box .reply-textarea"
    );

    confirmBtn.addEventListener("click", async () => {
        const content = replyTextarea.value.trim();
        if (!content) {
            showNotification("回复内容不能为空", "error");
            return;
        }

        try {
            await submitReply(comment.id, content);
            showNotification("回复成功");
            replyTextarea.value = "";
            commentElement.querySelector(".reply-box").style.display = "none";

            // 重新加载评论
            await showDemandMessages(
                currentSelectedDemandId,
                document.querySelector(".demand-name").textContent
            );
        } catch (error) {
            console.error("Error:", error);
            showNotification("发送回复失败：" + error.message, "error");
        }
    });
}

// 添加默认头像处理函数
function handleAvatarError(img) {
    img.onerror = null; // 防止循环调用
    img.src = "/images/default-avatar.png"; // 使用本地默认头像
}

// 创建评论元素
async function createCommentElement(comment, allReplies) {
    const commentElement = document.createElement("div");
    commentElement.className = "comment-item";
    commentElement.setAttribute("data-comment-id", comment.id);

    // 获取用户信息
    let userInfo;
    try {
        const userResponse = await fetch(`/api/user/info?userId=${comment.userId}`);
        if (!userResponse.ok) {
            throw new Error("获取用户信息失败");
        }
        userInfo = await userResponse.json();
    } catch (error) {
        console.error("Error fetching user info:", error);
        userInfo = {
            username: comment.userName,
            avatarUrl: "/images/default-avatar.png",
        };
    }

    // 过滤出当前评论的回复
    const commentReplies = allReplies.filter(
        (reply) => reply.parentId === comment.id
    );

    commentElement.innerHTML = `
      <div class="comment-avatar">
          <img src="${
        userInfo.avatarUrl || `/api/user/avatar/image/${comment.userId}`
    }" 
               alt="用户头像" 
               onerror="handleAvatarError(this)">
      </div>
      <div class="comment-content">
          <div class="comment-user">${
        userInfo.username || comment.userName
    }</div>
          <div class="comment-text">${comment.content}</div>
          <div class="comment-actions">
              <span class="comment-time">${formatDateTime(
        comment.createdTime
    )}</span>
              <button class="reply-button">回复</button>
          </div>
          ${
        commentReplies.length > 0
            ? `
              <div class="replies-preview">
                  <div class="replies-count">查看 ${
                commentReplies.length
            } 条回复</div>
                  <div class="replies-list" style="display: none;">
                      ${await createRepliesHTML(commentReplies)}
                  </div>
              </div>
          `
            : ""
    }
          <div class="reply-box" style="display: none;">
              <div class="reply-avatar">
                  <img src="${
        userInfo.avatarUrl || `/api/user/avatar/image/${userId}`
    }" 
                       alt="当前用户头像"
                       onerror="handleAvatarError(this)">
              </div>
              <div class="reply-input-container">
                  <textarea class="reply-textarea" placeholder="回复 ${
        userInfo.username || comment.userName
    }"></textarea>
                  <button class="confirm-btn">发送</button>
              </div>
          </div>
      </div>
  `;

    // 添加回复按钮事件
    const replyButton = commentElement.querySelector(".reply-button");
    const replyBox = commentElement.querySelector(".reply-box");
    replyButton.addEventListener("click", () => {
        replyBox.style.display =
            replyBox.style.display === "none" ? "flex" : "none";
    });

    // 添加回复列表展开/收起事件
    const repliesCount = commentElement.querySelector(".replies-count");
    const repliesList = commentElement.querySelector(".replies-list");
    if (repliesCount && repliesList) {
        repliesCount.addEventListener("click", () => {
            const isHidden = repliesList.style.display === "none";
            repliesList.style.display = isHidden ? "block" : "none";
            repliesCount.textContent = isHidden
                ? `收起回复`
                : `查看 ${commentReplies.length} 条回复`;
        });
    }

    // 添加发送回复事件
    const confirmBtn = commentElement.querySelector(".reply-box .confirm-btn");
    const replyTextarea = commentElement.querySelector(
        ".reply-box .reply-textarea"
    );
    confirmBtn.addEventListener("click", async () => {
        const content = replyTextarea.value.trim();
        if (!content) {
            showNotification("回复内容不能为空", "error");
            return;
        }

        try {
            const reply = {
                content: content,
                demandId: currentSelectedDemandId,
                userId: userId,
                userName: `专家 ${userEmail}`,
                parentId: comment.id,
                isRead: false,
            };

            const response = await fetch(`/api/comments/${comment.id}/reply`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(reply),
            });

            if (!response.ok) {
                throw new Error("发送回复失败");
            }

            showNotification("回复成功");
            replyTextarea.value = "";
            replyBox.style.display = "none";

            // 重新加载评论
            showDemandMessages(
                currentSelectedDemandId,
                document.querySelector(".demand-name").textContent
            );
        } catch (error) {
            console.error("Error:", error);
            showNotification("发送回复失败：" + error.message, "error");
        }
    });

    return commentElement;
}

// 创建回复列表HTML
async function createRepliesHTML(replies) {
    let html = "";
    // 按时间正序排列回复
    replies.sort((a, b) => new Date(a.createdTime) - new Date(b.createdTime));

    for (const reply of replies) {
        let userInfo;
        try {
            const userResponse = await fetch(`/api/user/info?userId=${reply.userId}`);
            if (!userResponse.ok) {
                throw new Error("获取用户信息失败");
            }
            userInfo = await userResponse.json();
        } catch (error) {
            console.error("Error fetching user info:", error);
            userInfo = {
                username: reply.userName,
                avatarUrl: "/images/default-avatar.png",
            };
        }

        html += `
        <div class="reply-item">
            <div class="comment-avatar">
                <img src="${
            userInfo.avatarUrl || `/api/user/avatar/image/${reply.userId}`
        }" 
                     alt="用户头像"
                     onerror="handleAvatarError(this)">
            </div>
            <div class="comment-content">
                <div class="comment-user">${
            userInfo.username || reply.userName
        }</div>
                <div class="comment-text">${reply.content}</div>
                <div class="comment-actions">
                    <span class="comment-time">${formatDateTime(
            reply.createdTime
        )}</span>
                </div>
            </div>
        </div>
    `;
    }
    return html;
}

// 更新发送主评论的事件处理
document
    .querySelector(".main-reply .confirm-btn")
    .addEventListener("click", async () => {
        const replyTextarea = document.querySelector(".main-reply .reply-textarea");
        const replyContent = replyTextarea.value.trim();

        if (!replyContent) {
            showNotification("评论内容不能为空", "error");
            return;
        }

        if (!currentSelectedDemandId) {
            showNotification("请先选择一个需求", "error");
            return;
        }

        try {
            const commentData = {
                content: replyContent,
                demandId: currentSelectedDemandId,
                userId: userId,
                userName: `专家 ${userEmail}`,
                isRead: false,
                parentId: null, // 主评论
            };

            const response = await fetch("/api/comments", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(commentData),
            });

            if (!response.ok) {
                throw new Error("发送评论失败");
            }

            showNotification("评论发送成功");
            replyTextarea.value = "";

            // 重新加载评论列表
            showDemandMessages(
                currentSelectedDemandId,
                document.querySelector(".demand-name").textContent
            );
        } catch (error) {
            console.error("Error:", error);
            showNotification("发送评论失败：" + error.message, "error");
        }
    });

// 格式化日期时间
function formatDateTime(dateStr) {
    if (!dateStr) return "未知时间";
    try {
        const date = new Date(dateStr);
        return date.toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
            hour12: false,
        });
    } catch (e) {
        return dateStr;
    }
}

// 标记评论为已读
async function markCommentAsRead(commentId) {
    try {
        const response = await fetch(`/api/comments/${commentId}/read`, {
            method: "PUT",
        });
        if (!response.ok) {
            throw new Error("标记评论已读失败");
        }
    } catch (error) {
        console.error("Error marking comment as read:", error);
    }
}

// 批量标记评论为已读
async function markCommentsAsRead(comments) {
    for (const comment of comments) {
        if (!comment.isRead) {
            await markCommentAsRead(comment.id);
        }
    }
}

// 生成回复预览HTML
function generateRepliesPreviewHTML(replies) {
    if (replies.length === 0) return "";
    return `
    <div class="replies-preview">
      <div class="replies-count">查看 ${replies.length} 条回复</div>
      <div class="replies-list" style="display: none;">
        ${generateRepliesListHTML(replies)}
      </div>
    </div>
  `;
}

// 生成回复列表HTML
function generateRepliesListHTML(replies) {
    return replies
        .map(
            (reply) => `
        <div class="reply-item">
          <div class="comment-avatar">
            <img src="${
                reply.avatarUrl || `/api/user/avatar/image/${reply.userId}`
            }" 
                 alt="用户头像"
                 onerror="handleAvatarError(this)"
                 loading="lazy">
          </div>
          <div class="comment-content">
            <div class="comment-user">${reply.userName}</div>
            <div class="comment-text">${reply.content}</div>
            <div class="comment-actions">
              <span class="comment-time">${formatDateTime(
                reply.createdTime
            )}</span>
            </div>
          </div>
        </div>
      `
        )
        .join("");
}

// 生成回复框HTML
function generateReplyBoxHTML(userInfo) {
    return `
    <div class="reply-box" style="display: none;">
      <div class="reply-avatar">
        <img src="${userInfo.avatarUrl || `/api/user/avatar/image/${userId}`}" 
             alt="当前用户头像"
             onerror="handleAvatarError(this)">
      </div>
      <div class="reply-input-container">
        <textarea class="reply-textarea" placeholder="回复 ${
        userInfo.username
    }"></textarea>
        <button class="confirm-btn">发送</button>
      </div>
    </div>
  `;
}

// 提交回复
async function submitReply(commentId, content) {
    const reply = {
        content: content,
        demandId: currentSelectedDemandId,
        userId: userId,
        userName: `专家 ${userEmail}`,
        parentId: commentId,
        isRead: false,
    };

    const response = await fetch(`/api/comments/${commentId}/reply`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(reply),
    });

    if (!response.ok) {
        throw new Error("发送回复失败");
    }

    return response.json();
}

// 用户信息下拉菜单
document.querySelector(".user-info").addEventListener("click", function () {
    const dropdown = this.querySelector(".user-dropdown");
    dropdown.style.display =
        dropdown.style.display === "block" ? "none" : "block";
});

// 修改密码按钮逻辑
document
    .getElementById("change-password-btn")
    .addEventListener("click", function () {
        document.querySelector(".change-password-container").style.display = "flex";
        document.querySelector(".user-dropdown").style.display = "none";
    });

// 返回按钮逻辑
document
    .getElementById("return-to-user-info")
    .addEventListener("click", function () {
        document.querySelector(".change-password-container").style.display = "none";
        document.querySelector(".user-dropdown").style.display = "block";
    });

// 获取验证码按钮逻辑
document
    .getElementById("get-verification-code")
    .addEventListener("click", async function () {
        const userContact = document.getElementById("user-contact-display").value;

        try {
            const response = await fetch("/api/sendVerificationCode", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    account: userEmail, // 使用全局的userEmail变量
                }),
            });

            const result = await response.json();

            if (result.success) {
                showNotification("验证码已发送到您的邮箱，请查收");

                // 倒计时功能
                let countdown = 60;
                this.disabled = true;
                this.textContent = `${countdown}秒后重试`;

                const timer = setInterval(() => {
                    countdown--;
                    this.textContent = `${countdown}秒后重试`;

                    if (countdown <= 0) {
                        clearInterval(timer);
                        this.disabled = false;
                        this.textContent = "获取";
                    }
                }, 1000);
            } else {
                showNotification(result.message || "验证码发送失败", "error");
            }
        } catch (error) {
            console.error("Error sending verification code:", error);
            showNotification("验证码发送失败，请稍后重试", "error");
        }
    });

// 确认修改密码按钮逻辑
document
    .getElementById("confirm-change-password")
    .addEventListener("click", async function () {
        const verificationCode = document.getElementById("verification-code").value;
        const newPassword = document.getElementById("new-password").value;
        const confirmPassword = document.getElementById("confirm-password").value;

        // 前端验证
        if (!verificationCode) {
            showNotification("请输入验证码", "error");
            return;
        }

        if (!newPassword) {
            showNotification("请输入新密码", "error");
            return;
        }

        if (!confirmPassword) {
            showNotification("请确认新密码", "error");
            return;
        }

        if (newPassword !== confirmPassword) {
            showNotification("两次输入的密码不一致", "error");
            return;
        }

        if (newPassword.length < 6) {
            showNotification("密码长度不能少于6位", "error");
            return;
        }

        try {
            const response = await fetch("/api/changePassword", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    account: userEmail,
                    verificationCode: verificationCode,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword,
                }),
            });

            const result = await response.json();

            if (result.success) {
                showNotification("密码修改成功");
                // 清空输入框
                document.getElementById("verification-code").value = "";
                document.getElementById("new-password").value = "";
                document.getElementById("confirm-password").value = "";
                // 关闭修改密码界面
                document.querySelector(".change-password-container").style.display =
                    "none";
            } else {
                showNotification(result.message || "密码修改失败", "error");
            }
        } catch (error) {
            console.error("Error changing password:", error);
            showNotification("密码修改失败，请稍后重试", "error");
        }
    });

// 头像上传相关功能
document
    .getElementById("uploadAvatarBtn")
    .addEventListener("click", function (e) {
        e.preventDefault();
        document.getElementById("avatarInput").click();
    });

// 页面加载时获取用户信息
async function loadUserInfo() {
    try {
        const response = await fetch(`/api/user/info?userId=${userId}`);
        if (!response.ok) {
            throw new Error("获取用户信息失败");
        }

        const userInfo = await response.json();
        console.log("User info:", userInfo);

        // 更新用户信息显示
        document.getElementById("user-contact").textContent =
            userInfo.contact || userEmail;
        document.getElementById("userEmail").textContent =
            userInfo.contact || userEmail;

        // 更新头像显示
        const avatarElement = document.querySelector(".avatar");
        if (avatarElement) {
            if (userInfo.avatarUrl) {
                // 尝试加载用户头像
                const img = new Image();
                img.onload = () => {
                    avatarElement.style.backgroundImage = `url('${userInfo.avatarUrl}')`;
                    avatarElement.classList.add("has-image");
                };
                img.onerror = () => {
                    // 如果远程头像加载失败，使用本地默认头像
                    avatarElement.style.backgroundImage =
                        "url('/images/default-avatar.png')";
                    avatarElement.classList.add("has-image");
                };
                img.src = userInfo.avatarUrl;
            } else {
                // 如果没有头像URL，使用本地默认头像
                avatarElement.style.backgroundImage =
                    "url('/images/default-avatar.png')";
                avatarElement.classList.add("has-image");
            }
        }
    } catch (error) {
        console.error("Error loading user info:", error);
        // 出错时也使用默认头像
        const avatarElement = document.querySelector(".avatar");
        if (avatarElement) {
            avatarElement.style.backgroundImage = "url('/images/default-avatar.png')";
            avatarElement.classList.add("has-image");
        }
    }
}

// 页面加载完成后执行
document.addEventListener("DOMContentLoaded", loadUserInfo);

// 文件上传处理
document
    .getElementById("avatarInput")
    .addEventListener("change", async function (e) {
        const file = e.target.files[0];
        if (!file) return;

        // 验证文件类型
        if (!file.type.startsWith("image/")) {
            alert("请选择图片文件！");
            return;
        }

        // 验证文件大小（限制为2MB）
        if (file.size > 2 * 1024 * 1024) {
            alert("图片大小不能超过2MB！");
            return;
        }

        try {
            // 创建FormData对象
            const formData = new FormData();
            formData.append("avatar", file);
            formData.append("userId", userId); // 使用实际的用户ID

            // 调用后端API上传头像
            const response = await fetch("/api/user/avatar", {
                method: "POST",
                body: formData,
            });

            if (!response.ok) {
                const result = await response.json();
                throw new Error(result.message || "上传失败");
            }

            const result = await response.json();
            console.log("Upload response:", result);

            // 更新头像显示
            if (result.avatarUrl) {
                // 直接使用返回的avatarUrl，它现在指向新的端点
                const avatarUrl = result.avatarUrl;
                console.log("Avatar URL:", avatarUrl);

                const avatarElement = document.querySelector(".avatar");
                avatarElement.style.backgroundImage = `url('${avatarUrl}')`;
                avatarElement.classList.add("has-image");
                showNotification("头像上传成功！");
            }
        } catch (error) {
            console.error("Upload error:", error);
            showNotification("上传头像失败：" + error.message, "error");
        }
    });

// 全局变量
let currentSelectedDemandId = null;
let currentPage = 0;
const pageSize = 12;
let totalPages = 1;
let currentTab = "需求广场";
let isTabSwitching = false;

// 初始化脑图渲染器
let currentMindmap = null;
let transformer = null;

// 等待markmap库加载完成的函数
function waitForMarkmap() {
    return new Promise((resolve) => {
        const check = () => {
            if (window.markmap && window.markmap.Markmap) {
                resolve();
            } else {
                setTimeout(check, 100);
            }
        };
        check();
    });
}

async function generateMindmap(markdownContent) {
    const container = document.getElementById("load-mindmap-container");
    if (!container) {
        console.error("找不到load-mindmap-container元素");
        return;
    }

    try {
        if (!markdownContent || markdownContent.trim() === "") {
            container.innerHTML =
                '<div class="mindmap-placeholder">请等待需求描述加载完成，将自动生成思维导图</div>';
            return;
        }

        // 等待markmap库加载
        await waitForMarkmap();

        // 如果内容不是markdown格式，尝试转换为简单的markdown结构
        let processedContent = markdownContent;
        if (
            !markdownContent.includes("#") &&
            !markdownContent.includes("*") &&
            !markdownContent.includes("-")
        ) {
            const lines = markdownContent.split("\n").filter((line) => line.trim());
            if (lines.length > 0) {
                processedContent = `# ${lines[0]}\n\n${lines
                    .slice(1)
                    .map((line) => `- ${line}`)
                    .join("\n")}`;
            }
        }

        // 初始化transformer（如果还没有）
        if (!transformer) {
            transformer = new window.markmap.Transformer();
        }

        // 使用markmap-lib解析markdown
        const { root } = transformer.transform(processedContent);

        // 初始化或更新markmap
        if (!currentMindmap || !container.querySelector("svg")) {
            // 清空容器
            container.innerHTML = "";

            // 创建SVG元素
            const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
            svg.style.width = "100%";
            svg.style.height = "100%";
            container.appendChild(svg);

            // 创建新的Markmap实例
            currentMindmap = new window.markmap.Markmap(svg, {
                autoFit: true,
                duration: 300,
                maxWidth: 300,
                color: (node) => {
                    const colors = [
                        "#4CAF50",
                        "#2196F3",
                        "#FF9800",
                        "#9C27B0",
                        "#F44336",
                    ];
                    return colors[node.depth % colors.length];
                },
            });
        }

        if (currentMindmap && root) {
            // 渲染思维导图
            currentMindmap.setData(root);
            currentMindmap.fit();
        }
    } catch (error) {
        console.error("生成思维导图失败:", error);
        container.innerHTML =
            '<div class="mindmap-placeholder">思维导图生成失败，请检查内容格式</div>';
        currentMindmap = null;
    }
}

async function showDemandDetail(demandId) {
    try {
        const response = await fetch(`/api/demands/${demandId}`);
        if (!response.ok) {
            throw new Error(`获取需求详情失败: ${response.status}`);
        }

        const demand = await response.json();

        // 隐藏需求广场，显示详情页面
        document.querySelector(".container").style.display = "none";
        const detailPage = document.querySelector(".demand-detail");
        detailPage.style.display = "flex";

        // 更新需求描述并生成脑图
        const descriptionElement = document.getElementById(
            "demand-description-view"
        );
        if (descriptionElement) {
            // 处理描述文本，保持换行和格式
            const formattedDescription = demand.description
                ? demand.description
                    .split("\n")
                    .map((line) => line.trim())
                    .join("\n\n")
                : "暂无描述";

            descriptionElement.innerHTML = `<pre>${formattedDescription}</pre>`;

            // 根据需求描述生成脑图
            if (demand.description) {
                await generateMindmap(demand.description);
            } else {
                const mindmapContainer = document.getElementById(
                    "load-mindmap-container"
                );
                if (mindmapContainer) {
                    mindmapContainer.innerHTML =
                        '<div class="mindmap-placeholder">暂无需求描述，无法生成思维导图</div>';
                }
            }
        }

        // 清空评论输入框
        const commentInput = detailPage.querySelector(".input-demand");
        if (commentInput) {
            commentInput.value = "";
        }

        // 绑定返回按钮事件
        const returnBtn = detailPage.querySelector(".return-btn");
        if (returnBtn) {
            returnBtn.onclick = () => {
                detailPage.style.display = "none";
                document.querySelector(".container").style.display = "flex";
            };
        }

        // 绑定提交评论按钮事件
        const submitBtn = detailPage.querySelector(".submit-btn");
        if (submitBtn) {
            submitBtn.onclick = async () => {
                const content = commentInput.value.trim();
                if (!content) {
                    showNotification("请输入评论内容", "error");
                    return;
                }

                try {
                    const commentData = {
                        content: content,
                        demandId: demandId,
                        userId: userId,
                        userName: `专家 ${userEmail}`,
                        isRead: false,
                    };

                    const response = await fetch("/api/comments", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify(commentData),
                    });

                    if (!response.ok) {
                        throw new Error("提交评论失败");
                    }

                    showNotification("评论提交成功！");
                    commentInput.value = "";
                } catch (error) {
                    console.error("提交评论失败:", error);
                    showNotification("提交评论失败：" + error.message, "error");
                }
            };
        }
    } catch (error) {
        console.error("显示需求详情失败:", error);
        showNotification("加载需求详情失败：" + error.message, "error");
    }
}

// 格式化需求状态
function formatDemandStatus(status) {
    const statusMap = {
        DRAFT: "草稿",
        PUBLISHED: "已发布",
        PROCESSING: "处理中",
        COMPLETED: "已完成",
        CANCELLED: "已取消",
    };
    return statusMap[status] || status;
}

// 创建需求卡片
function createDemandCard(demand) {
    const card = document.createElement("div");
    card.className = "demand-square";
    card.setAttribute("data-demand-id", demand.id);

    const creatorName = demand.creator
        ? demand.creator.username || demand.creator.email
        : "未知用户";

    card.innerHTML = `
    <div class="demand-title">${demand.title || "未命名需求"}</div>
    <div class="demand-description">${demand.description || "暂无描述"}</div>
    <div class="demand-status">${formatDemandStatus(demand.status)}</div>
    <div class="demand-creator">创建者：${creatorName}</div>
  `;

    card.addEventListener("click", () => showDemandDetail(demand.id));
    return card;
}

// 加载需求列表
async function loadDemands(page) {
    try {
        const demandGrid = document.querySelector(".demand-grid");
        demandGrid.innerHTML = "";

        // 创建加载占位符
        for (let i = 0; i < 12; i++) {
            const skeleton = document.createElement("div");
            skeleton.className = "demand-square loading-skeleton";
            demandGrid.appendChild(skeleton);
        }

        const url = new URL("/api/demands/main", window.location.origin);
        url.searchParams.append("page", page);
        url.searchParams.append("size", pageSize);
        url.searchParams.append("sort", "createdTime,desc");
        url.searchParams.append("excludeUserId", userId);

        const response = await fetch(url);
        if (!response.ok) {
            throw new Error("获取需求列表失败");
        }

        const data = await response.json();
        const demands = data.content || [];
        totalPages = data.totalPages || 1;

        // 更新分页信息
        updatePaginationControls(page, totalPages);

        // 清空加载占位符
        demandGrid.innerHTML = "";

        // 使用DocumentFragment优化DOM操作
        const fragment = document.createDocumentFragment();

        // 显示需求卡片
        demands.forEach((demand) => {
            const card = createDemandCard(demand);
            fragment.appendChild(card);
        });

        // 添加空白占位卡片
        const remainingSlots = pageSize - demands.length;
        for (let i = 0; i < remainingSlots; i++) {
            const emptyCard = document.createElement("div");
            emptyCard.className = "demand-square empty";
            emptyCard.style.visibility = "hidden";
            fragment.appendChild(emptyCard);
        }

        demandGrid.appendChild(fragment);
    } catch (error) {
        console.error("Error loading demands:", error);
        showNotification("加载需求列表失败：" + error.message, "error");
    }
}

// 更新分页控制器
function updatePaginationControls(currentPage, totalPages) {
    const prevBtn = document.getElementById("prev-page");
    const nextBtn = document.getElementById("next-page");
    const pageInfo = document.getElementById("page-info");

    prevBtn.disabled = currentPage === 0;
    nextBtn.disabled = currentPage >= totalPages - 1;
    pageInfo.textContent = `第 ${currentPage + 1} 页 / 共 ${totalPages} 页`;
}

// 显示通知
function showNotification(message, type = "success") {
    const notification = document.querySelector(".notification");
    const messageElement = notification.querySelector(".message");
    const iconElement = notification.querySelector(".icon");

    messageElement.textContent = message;
    notification.className = "notification";
    if (type === "error") {
        notification.classList.add("error");
        iconElement.textContent = "✕";
    } else {
        iconElement.textContent = "✓";
    }

    notification.classList.add("show");
    setTimeout(() => {
        notification.classList.remove("show");
    }, 3000);
}
